package com.dmall.directed.graph;

import java.util.ArrayList;
import java.util.Arrays;

public class CC {

    private Graph G;
    private final int[] visited;
    private int cccount = 0;

    public CC(Graph G) {
        if (G.isDirected()) {
            throw new IllegalArgumentException("CC only work in undirected graph.");
        }
        this.G = G;
        this.visited = new int[G.V()];
        Arrays.fill(this.visited, -1);

        for (int i = 0; i < G.V(); i++) {
            if (visited[i] == -1) {
                dfs(i, cccount);
                cccount ++;
            }
        }
    }

    private void dfs(int v, int ccid) {
        visited[v] = ccid;
        for (int w : G.adj(v)) {
            if (visited[w] == -1) {
                dfs(w, ccid);
            }
        }
    }

    public int count() {
        return cccount;
    }

    public boolean isCollected(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] components = new ArrayList[cccount];
        for (int i = 0; i < cccount; i++) {
            components[i] = new ArrayList<>();
        }
        for (int i = 0; i < G.V(); i++) {
            components[visited[i]].add(i);
        }
        return components;
    }

    public static void main(String[] args) {
        String filePath = CC.class.getClassLoader().getResource("com/dmall/directed/graph/ug5.txt").getPath();
        Graph graph = new Graph(filePath);
        CC cc = new CC(graph.reverseGraph());
        System.out.println(cc.count());
        ArrayList<Integer>[] components = cc.components();
        for (int ccid = 0; ccid < components.length; ccid ++) {
            System.out.print(ccid + " : ");
            for (int w : components[ccid]) {
                System.out.print(w + " ");
            }
            System.out.println();
        }
    }
}
